import com.adobe.webapis.flickr.FlickrService;
import com.adobe.webapis.flickr.events.FlickrResultEvent;

import de.yuv.flexplorr.components.XmlPreferences;
import de.yuv.flexplorr.components.myFlickrPhoto;
import de.yuv.flexplorr.events.SettingsButtonEvent;
import de.yuv.flexplorr.events.myFlickrPhotoEvent;

import flash.display.DisplayObject;
import flash.display.Screen;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.NativeWindowBoundsEvent;
import flash.filesystem.FileStream;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.utils.Timer;

import mx.controls.Alert;


	include "../../../../../_outsideSVN/flickrAPIkey.as";
	public var _flickr:FlickrService = new FlickrService(_flickrAPIkey);
	public var _photoList:Array = new Array();;
	public var _Timer:Timer;
	public var _Page:uint = 1;
	public var _perPage:uint = 20; //20
	
	public var _timeForOneImage:uint = 29; //29
	public var _numberOfImageRepeats:uint = 7; //7
	public var _photosOnScreen:Array;
	public var _photoCounter:uint = 0;
	public var _repeatCounter:uint = _numberOfImageRepeats;
	
	public var globalPrefs:XmlPreferences;
	
	public var prefsFile:File;
	public var prefsXML:XML;
	public var stream:FileStream;
	
	public var windowWasMoved:Boolean = false;
	
	public function appComplete():void
	{ 
		if (globalPrefs.preferences.windowState.@width.toString() != ""){
			trace('--------');
			nativeWindow.x = globalPrefs.preferences.windowState.@x;
			nativeWindow.y = globalPrefs.preferences.windowState.@y;
			nativeWindow.width = globalPrefs.preferences.windowState.@width;
			nativeWindow.height = globalPrefs.preferences.windowState.@height;
		}
		
		nativeWindow.addEventListener(Event.CLOSING, windowClosingHandler);
		nativeWindow.addEventListener(NativeWindowBoundsEvent.MOVE, onWindowMove);
	}
	
	public function onWindowMove(e:NativeWindowBoundsEvent):void{
		//trace('#################### onWindowMove');
		//trace(e.beforeBounds);
		//trace(e.afterBounds);
		//trace(Screen.screens.toString());
		//trace(Screen.mainScreen);
		//trace(Screen.mainScreen.bounds.toString());
		//trace("Screens for Rect: "+Screen.getScreensForRectangle(e.afterBounds).length);
		if (Screen.getScreensForRectangle(e.afterBounds).length == 0
			
		){
			nativeWindow.x = Screen.mainScreen.visibleBounds.x+20;
			nativeWindow.y = Screen.mainScreen.visibleBounds.y+20;
			nativeWindow.width = Screen.mainScreen.visibleBounds.width-40;
			nativeWindow.height = Screen.mainScreen.visibleBounds.height-40;
			
			
		}
		
		windowWasMoved = !(e.afterBounds.toString() == e.beforeBounds.toString());
		//windowWasMoved = true;
	}
	
	
	public function init():void{
		windowWasMoved = false;
		Multitouch.inputMode = MultitouchInputMode.GESTURE;
		_photosOnScreen = new Array();
		
		globalPrefs = new XmlPreferences('preferences.xml');
		globalPrefs.load();
		if (globalPrefs.preferences.flickrsetting.@which.toString() == "") globalPrefs.preferences.flickrsetting.@which = "Interesting";
		if (globalPrefs.preferences.flickrsetting.@size.toString() == "") globalPrefs.preferences.flickrsetting.@size = "_m";
		if (globalPrefs.preferences.flickrsetting.tags.toString() == "") globalPrefs.preferences.flickrsetting.tags = "beach, sun";
		if (globalPrefs.preferences.flickrsetting.groupname.toString() == "") globalPrefs.preferences.flickrsetting.groupname = "zoo";
		if (globalPrefs.preferences.flickrsetting.groupname.@groupid.toString() == "") globalPrefs.preferences.flickrsetting.groupname.@groupid = "52241775676@N01";
		_flickr.addEventListener(Event.ACTIVATE,onFlickrEvent);
		_flickr.addEventListener(FlickrResultEvent.INTERESTINGNESS_GET_LIST, onFlickrEventGetInteresting);
		_flickr.addEventListener(FlickrResultEvent.GROUPS_POOLS_GET_PHOTOS, onFlickrEventGetGroupPhotos);
		_flickr.addEventListener(FlickrResultEvent.PHOTOS_SEARCH, onFlickrEventPhotosSearch);
		
		_flickr.addEventListener(IOErrorEvent.IO_ERROR, onFlickrError);
		
		_Timer = new Timer(5000);
		_Timer.addEventListener(TimerEvent.TIMER, onTick);
		
		
		
		
		//_flickr.interestingness.getList(null,'',_perPage,_Page);
		
		settings.addEventListener(SettingsButtonEvent.EXIT_BUTTON,windowClosingHandler);
		reset();
	}
	
	public function reset():void{
		_Timer.stop();
		settings.visible = false;
		for (var i:uint = 0; i<	_photosOnScreen.length;i++){	
			_photosOnScreen[i].alpha = 0;
		
		}
		_photoList = new Array();
		_photoCounter = 0;
		_repeatCounter = _numberOfImageRepeats
		showNextImage();
		
	}
	
	public function getThePhotoList():void{
		//trace('getThePhotoList:');
		//trace(globalPrefs.preferences.flickrsetting.@which)
		_Timer.stop();
		switch (globalPrefs.preferences.flickrsetting.@which.toString()){
			case "Group":
				_flickr.groups.pools.getPhotos(globalPrefs.preferences.flickrsetting.groupname.@groupid,"","",_perPage,_Page);
							
			break;
			case "Tags":
				_flickr.photos.search("",globalPrefs.preferences.flickrsetting.tags,"any","",null,null,null,null,-1,"date-posted-desc",-1,"",-1,-1,-1,"","","","","","","",false,"","",-1,-1,"",_perPage,_Page);
				//_flickr.photos.search(
			break;
			default:
				_flickr.interestingness.getList(null,'',_perPage,_Page);
			break;
		}
	}
	
	public function onFlickrEvent(ev:Event):void{
		//trace('onFlickrEvent');
		nativeWindow.activate();
		nativeWindow.alwaysInFront = globalPrefs.preferences.windowState.@alwaysinfront.toString() == "true" ? true : false;
		nativeWindow.activate();
		showNextImage();
		
	}
	
	public function onFlickrError(ev:Event):void{
		//trace('onFlickrError');
		Alert.show("Couldn't connect to the Flickr API!\nPlease make sure you are connected to the internet and start application again.", "Connection Error", Alert.OK);

		
	}
	
	public function onFlickrEventGetInteresting(ev:FlickrResultEvent):void{
		
		//http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}.jpg
		//trace('onFlickrEventInteresting');
		_photoList = new Array();
		_photoList = ev.data.photos.photos;
		showNextImage();
		
		_Timer.start();
		//trace(_flickr.interestingness);
	}
	
	public function onFlickrEventGetGroupPhotos(ev:FlickrResultEvent):void{
		//trace('onFlickrEventGetGroupPhotos');
		_photoList = new Array();
		_photoList = ev.data.photos.photos;
		showNextImage();
		
		_Timer.start();
	}
	
	public function onFlickrEventPhotosSearch(ev:FlickrResultEvent):void{
		//trace('onFlickrEventGetGroupPhotos');
		_photoList = new Array();
		_photoList = ev.data.photos.photos;
		showNextImage();
		
		_Timer.start();
	}
	
	public function showNextImage():Boolean{
		//trace('showNextImage:')
		//trace('_repeatCounter:'+_repeatCounter);
		//trace('_photoCounter:'+_photoCounter);
		if (_repeatCounter%_numberOfImageRepeats == 0){
			//trace('neue Bilder sind dran');
			
			if (_photoList.length == 0){
				//trace('sind noch keine geladen');
				getThePhotoList();
				_Page++
				if (_Page > 500/_perPage) _Page = 1;
				return true;
			}
			//trace('noch drin?')
			if (!_photosOnScreen[_photoCounter]){
				_photosOnScreen[_photoCounter] = new myFlickrPhoto();
				_photosOnScreen[_photoCounter].flickrPhoto = _photoList[_photoCounter];
				_photosOnScreen[_photoCounter].size = globalPrefs.preferences.flickrsetting.@size;
				_photosOnScreen[_photoCounter].time = _timeForOneImage;
				_photosOnScreen[_photoCounter].alpha = 0;
				this.addChild(_photosOnScreen[_photoCounter]);
				_photosOnScreen[_photoCounter].addEventListener(myFlickrPhotoEvent.ROLLOVER,onFlickrPhotoClick);
			} else {
				_photosOnScreen[_photoCounter].flickrPhoto = _photoList[_photoCounter];
				_photosOnScreen[_photoCounter].reload();
			}
			// wenn alle gesetzt _photoList leermachen
			if (_photoCounter == _photoList.length-1){
				//trace('_photoList leermachen');
				_photoList = new Array();
			}
		} else {
			//trace('alte Bilder noch mal zeigen');
			_photosOnScreen[_photoCounter].blendIn();
		}
		setChildIndex(_photosOnScreen[_photoCounter],numChildren-1);
		beamSettingsToTop();
		_photoCounter++;
		
		if (_photoCounter == _perPage){
			_photoCounter = 0;
			_repeatCounter++;
		}
		
		return false;
	}
	
	public function onTick(event:TimerEvent):void 
    {
        showNextImage();
    }
	
	public function showSettings():void{
		//trace('------------showSettings: '+windowWasMoved);
		if (!windowWasMoved){
			settings.visible = !settings.visible
			beamSettingsToTop();
		} 
		windowWasMoved = false;
	}
	
	public function beamSettingsToTop():void{
		//trace('beamSettingsToTop: '+numChildren);
		setChildIndex(settings, numChildren-1);
		
	}
	
	public function setMeToTop(__me:DisplayObject):void{
		setChildIndex(__me, numChildren-1);
		beamSettingsToTop();
		
	}
	
	public function onFlickrPhotoClick(ev:myFlickrPhotoEvent):void{
		//trace('onFlickrPhotoClick'+ev);
		setMeToTop(ev.target as DisplayObject);
	}
	
	public function windowClosingHandler(event:Event):void {
		if (Capabilities.os.indexOf("Mac") === -1) event.preventDefault();
		globalPrefs.preferences.windowState.@width = nativeWindow.width;
		globalPrefs.preferences.windowState.@height = nativeWindow.height;
		globalPrefs.preferences.windowState.@x = nativeWindow.x;
		globalPrefs.preferences.windowState.@y = nativeWindow.y;
		globalPrefs.preferences.windowState.@alwaysinfront = nativeWindow.alwaysInFront;
		globalPrefs.save();
		exit();
	}



